package com.mx.gulimallproduct.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mx.common.utils.PageUtils;
import com.mx.common.utils.Query;

import com.mx.gulimallproduct.dao.CategoryDao;
import com.mx.gulimallproduct.entity.CategoryEntity;
import com.mx.gulimallproduct.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有的类型
        List<CategoryEntity> entities=baseMapper.selectList(null);
        //2、组装树形结构
        //2.1、查找所有的一级分类
        List<CategoryEntity> firstLevelList = entities.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(item -> {
                    item.setChildren(getChildren(item, entities));
                    return item;
                }).sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());
        //2.2、
        return firstLevelList;
    }

    private List<CategoryEntity> getChildren(CategoryEntity entity, List<CategoryEntity> all) {
        List<CategoryEntity> list = all.stream()
                .filter(item -> item.getParentCid() == entity.getCatId())
                .map(item -> {
                    item.setChildren(getChildren(item, all));
                    return item;
                })
                .sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                }).collect(Collectors.toList());
        return list;
    }
}